import React, {Component, Fragment} from "react";
import './style.css';
import TodoItem from './TodoItem';
import PropTypes from 'react';

/**
 * TodoList
 *
 * 自定义组件，组件抽取，item 增删，子组件与父组件通信参数传递，函数传递（handleItemDelete），结解化赋值，
 *
 * setState
 * this.setState((prevState) =>({
 *     //prevState 修改之前的state数据
 * }))
 *
 *
 */

class TodoList extends Component {

    constructor(props) {
        super(props);
        //当组件的state 或者props发生改变时，render会重新执行
        this.state = {
            inputValue: '',
            list: PropTypes.array
        };
        this.handleBtnClick = this.handleBtnClick.bind(this);
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleItemDelete = this.handleItemDelete.bind(this);
    }

    render() {
        console.log('render');
        return (
            <Fragment>
                <div>
                    <label htmlFor="inputArea">输入内容：</label>
                    <input id="inputArea" className='input' value={this.state.inputValue}
                           onChange={this.handleInputChange}/>
                    <button onClick={this.handleBtnClick}>提交</button>
                </div>
                <ul>
                    {
                        this.getTodoItem()
                    }
                </ul>
            </Fragment>
        )
    }

    getTodoItem() {
        return this.state.list.map((item, index) => {
            // return <li key={index} onClick={this.handleItemDetlete.bind(this,index)}>{item}</li>
            console.log('item index=',index);
            return <TodoItem key={index} content={item} position={index} deleteItem={this.handleItemDelete}/>
        })
    }

    handleInputChange(e) {
        // this.setState({
        //     inputValue: e.target.value
        // })

        const value = e.target.value;
        this.setState(() => ({
            inputValue: value
        }));
    }

    handleBtnClick() {
        const inputValue = this.state.inputValue;

        if (inputValue === '')
            return
        // this.setState({
        //     list: [...this.state.list, this.state.inputValue],
        //     inputValue: ''
        // })

        // this.setState(()=>({
        //     list:[...this.state.list,inputValue],
        //     inputValue : ''
        // }))

        //prevState 修改数据之前的
        this.setState((prevState) => ({
            list: [...prevState.list, inputValue],
            inputValue: ''
        }))
    }

    handleItemDelete(index) {
        // const list = [...this.state.list];
        // list.splice(index, 1);
        // this.setState({
        //     list: list
        // })
        // this.setState(()=>({
        //     list:list
        // }));
        this.setState((prevState) => {
            //es6 list:list
            const list = [...prevState.list];
            list.splice(index, 1);
            return {list}
        });
        console.log(index);
    }
}


export default TodoList;